<script setup lang="ts">
import { ElMessage, type FormInstance, type FormRules, type UploadRequestOptions } from 'element-plus';
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router';
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { getArticleDetailApi, publishApi, tupian } from '@/apis/publish';
import type { PublishDataType } from '@/types/publish';

const queryDraft = ref<boolean>(false)
const articeForm = ref<PublishDataType>({
    title: '', // 文章标题
    content: '1', // 文章内容
    cover: {
        type: 1, // 封面类型 -1自动 0无图 1单图 3三图
        images: [] // 封面图片数据
    },
    channel_id:undefined
})

const formRef = ref<FormInstance>()
const fabu = (flag: boolean) => {
    // 表单验证
    formRef.value?.validate(async (valid: boolean) => {
        // 表单验证失败
        if (!valid) {
            ElMessage({ message: '请填写完整', type: 'error' });
            return
        }
        await publishApi(articeForm.value, queryDraft.value)
        router.push('/article')
        ElMessage('发布成功')
    })
}
const router = useRouter()
const route = useRoute()
// const checkCoverFn = (_, cover, callback):string => {
//     if (cover.type === 1 && cover.images.length < 1) {
//         return callback(new Error('请上传一张封面'))
//     } else if (cover.type === 3 && cover.images.length < 3) {
//         return callback(new Error('请上传三张封面'))
//     }
//     // 通过校验
//     callback()
// }
const articeRules = ref<FormRules>({
    title: [
        { required: true, message: '请输入文章标题', trigger: 'blur' },
        { min: 4, max: 50, message: '文章标题长度在4-50个字符之间', trigger: 'blur' }
    ],
    channel_id: [
        { required: true, message: '请选择文章频道', trigger: 'change' }
    ],
    content: [
        { required: true, message: '请输入文章内容', trigger: 'blur' }
    ],
    cover: [
        { required: true, trigger: 'change' }
    ]
})

const uploadFile = async (options: UploadRequestOptions) => {
    console.log('options', options);
    //1.准备FormData对象
    const fd = new FormData()
    //2.根据后端要求准备字段
    fd.append('image', options.file)
    //3.调用接口上传文件
    const res = await tupian(fd)
    console.log('数据8888',res);
    
    //添加图片地址
    articeForm.value.cover.images.push(res.data.url)
    return res.data.url
}

const itemID = route.params.id
const gethuixian = async () => {
    try {
        const res = await getArticleDetailApi(itemID as string)
        console.log('数据回显',res);
        
        const { title, content, cover, channel_id } = res.data
        articeForm.value = {
            title,
            content,
            cover,
            channel_id
        }
    } catch (a) {
        ElMessage('文章不存在')
        router.push('/article')
    }
}
if (itemID) {
    gethuixian()
}
</script>
<template>
    <el-card shadow="always" width="100%">
        <!-- 头部 -->
        <template v-slot:header>
            <div>
                <el-breadcrumb separator-class="el-ico
                n-arrow-right">
                    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                    <template v-if="$route.params.id">
                        <el-breadcrumb-item><a href="/article">返回主页</a></el-breadcrumb-item>
                        <el-breadcrumb-item>修改文章</el-breadcrumb-item>
                    </template>
                    <el-breadcrumb-item v-else><a href="/">发布文章</a></el-breadcrumb-item>
                </el-breadcrumb>
            </div>
        </template>
        <!-- 表单 -->
        <el-form ref="formRef" :model="articeForm" :rules="articeRules" label-width="120px">
            <el-form-item label="标题:" prop="title">
                <el-input v-model="articeForm.title" placeholder="请输入文章标题" style="width:400px"></el-input>
            </el-form-item>

            <el-form-item style="width:400px" label="频道:" prop="channel_id">
                <el-select v-model="articeForm.channel_id" placeholder="请选择" style="width:400px">
                    <el-option label="测试" value="0"></el-option>
                    <el-option label="Vue" value="1"></el-option>
                    <el-option label="React" value="2"></el-option>
                    <el-option label="Node" value="3"></el-option>
                </el-select>
                <GeekChannel v-model="articeForm.channel_id" />
            </el-form-item>

            <el-form-item label="封面" prop="cover">
                <el-radio-group v-model="articeForm.cover.type">
                    <el-radio :label="1">单图</el-radio>
                    <el-radio :label="3">三图</el-radio>
                    <el-radio :label="0">无图</el-radio>
                    <el-radio :label="-1">自动</el-radio>
                </el-radio-group>
                <!-- el-upload 上传组件参数
       action 必选参数，上传的地址
       list-type 文件列表的类型 text(文本)/priture(图片)
       http-request 覆盖默认的上传行为,可以自定义上传的实现-->
                <div v-if="articeForm.cover.type === 1 || articeForm.cover.type === 3">
                    <el-upload ref="uploadRef" action="" list-type="picture-card" :http-request="uploadFile"
                        :limit="articeForm.cover.type"
                        :file-list="articeForm.cover.images.map(url => ({ name: url, url: url, response: url }))">
                        <i class="el-icon-plus">+</i>
                    </el-upload>
                </div>
            </el-form-item>
            <el-form-item label="内容:" prop="content">
                <div>
                    <quill-editor theme="snow" v-model="articeForm.content"></quill-editor>
                </div>
            </el-form-item>

            <el-form-item label="" v-if="$route.params.id">
                <el-button type="primary">发布文章</el-button>
                <el-button>存为草稿</el-button>
                {{ articeForm }}
            </el-form-item>

            <el-form-item label="" v-else>
                <el-button type="primary" @click="fabu(false)">发布文章</el-button>
                <el-button @click="fabu(true)">存为草稿</el-button>
                {{ articeForm }}
            </el-form-item>
        </el-form>
    </el-card>
</template>
<style scoped>
::v-deep .ql-editor {
    min-height: 300px
}
::v-deep .el-form-item__content{
    display: block;
}
</style>